<script lang="ts" setup>
import { ref, onMounted, nextTick, computed } from 'vue'
import { ElMessage, ElTree } from 'element-plus'
import { Calendar, Search } from '@element-plus/icons-vue'
import TreeUtilDTO from '@/utils/tree'
import { useMainStore } from '@/store/main'
import { useRoute } from 'vue-router'
import yspglService from '@/api/yspgl'
import { getFldm } from '@/utils/get-fldm'
import { cloneDeep } from 'lodash'
import dayjs from 'dayjs'

const emit = defineEmits(['refresh'])

const store = useMainStore()
const route = useRoute()
// 入参

const form = ref({
  gjz: '',
  xgfsdm: '1',
  xgfsmc: '固定填充',
  xgzddm: '',
  xgzdmc: '',
})

const defaultProps = {
  children: 'children',
  label: 'mc',
}

const firtsNode = ref<any>()

/*
 * 树节点点击（抛出方法到主界面）
 */
const treeNodeData = ref()
const treeNodeClick = (data: any) => {
  treeNodeData.value = data
  form.value.gjz = ''
  queryForm.value = {
    tcnrValue: '',
    cznrValue: '',
    thnrValue: '',
    dqzjValue: '',
    dhzjValue: '',
  }
}

/**
 * 树节点过滤
 */
const filtersNode = (value: any, data: any) => {
  let flag = true
  if (value) {
    if (typeof value === 'string') {
      // 文字过滤
      flag = data[defaultProps.label].indexOf(value) !== -1
    }
  }
  return flag
}

// 扁平化
const treeToArray = (data: any[], props = { children: 'children' }) => {
  const data1 = cloneDeep(data)
  const { children } = props
  const newData = []
  const queue: any[] = []
  data1.forEach((child: any) => queue.push(child))
  while (queue.length) {
    const item: any = queue.shift()
    if (item[children]) {
      item[children].forEach((child: any) => queue.push(child))
      delete item[children]
    }
    newData.push(item)
  }
  return newData
}

/*
 * 查询案卷目录
 */
const treeData = ref<any[]>([])
const treeData1 = ref<any[]>([])
const queryTree = () => {
  //处理数据
  const params = {
    ajmc: route.query.ajmc as unknown as string,
    ajbh: route.query.ajbh as unknown as string,
  }
  yspglService
    .querySxmls(params)
    .then((res) => {
      let obj = route.query
      res.data.forEach((item: any) => {
        if (!item.fbh) {
          item['fbh'] = obj.ajbh
        }
      })
      //处理数据
      res.data.push({
        ajbh: obj.ajbh,
        bh: obj.ajbh,
        mc: obj.ajmc,
        wjsl: 0,
      })

      const newArr = treeToArray(res.data)

      if (
        store.$state.nodeTreeData?.mllxdm === 'gd0020002' ||
        store.$state.nodeTreeData?.mllxdm === 'gd0020001' ||
        store.$state.nodeTreeData?.bh === 'gd0020002' ||
        store.$state.nodeTreeData?.bh === 'gd0020001'
      ) {
        treeData1.value = newArr.filter(
          (item: any) => item.mllxdm !== 'gd0020003' && item.bh !== 'gd0020003',
        )
      } else {
        treeData1.value = newArr.filter((item: any) => {
          if (
            item.mllxdm !== 'gd0020001' &&
            item.bh !== 'gd0020001' &&
            item.mllxdm !== 'gd0020002' &&
            item.bh !== 'gd0020002'
          ) {
            return item
          }
        })
      }

      treeData.value = TreeUtilDTO.getTreeData(treeData1.value, 'bh', 'fbh')
      treeData.value?.forEach((data: any) => {
        if (data.children && data.children.length > 0) {
          data.children.forEach((data1: any) => {
            data.wjsl += Number(data1.wjsl)
            if (data1.children) {
              data1.children = data1.children.sort((a: any, b: any) => a.mlsxh - b.mlsxh)
            }
          })
        }
      })
      if (treeData.value.length) {
        firtsNode.value = null
        // 递归选择第一个
        getFirstNode(treeData.value)
        // 递归添加目录顺序号
        getSxhNode(treeData.value)
        if (firtsNode.value) {
          handleCheckNode(firtsNode.value)
        }
      }
    })
    .catch((err) => {
      !err.isError && ElMessage({ type: 'warning', message: err.message })
    })
}

const getFirstNode = (arr: any[]) => {
  if (firtsNode.value) return
  for (let i = 0; i < arr.length; i++) {
    if (arr[i].children && arr[i].children.length > 0) {
      getFirstNode(arr[i].children)
    } else {
      firtsNode.value = arr[i]
    }
    return
  }
}

const getSxhNode = (arr: any[]) => {
  for (let i = 0; i < arr.length; i++) {
    if (arr[i].children && arr[i].children.length > 0) {
      getFirstNode(arr[i].children)
    } else {
      arr[i].mlsxh = arr[i]
    }
  }
}

const handleCheckNode = (node: any) => {
  treeNodeClick(node)
  nextTick(() => {
    treeRef.value!.setCurrentKey(node.bh)
  })
}

// 获取修改字段
const xgzdList = ref<any>([])
const getXgzd = () => {
  const params = {
    mllxdm: store.$state.nodeTreeData?.mllxdm || store.$state.nodeTreeData?.bh,
  }
  yspglService
    .queryYspzd(params)
    .then((res) => {
      xgzdList.value = res.data
      xgzdChange(0)
    })
    .catch((err) => {
      !err.isError && ElMessage({ type: 'warning', message: err.message })
    })
}

/*
 * 树节点勾选
 */
const treeRef = ref<InstanceType<typeof ElTree>>()
const treeNodeCheck = () => {
  const nodes = treeRef.value?.getCheckedNodes() as any
  // checkNodes.value = nodes || []
}

const dialogVisible = ref(false)
/*
 * 打开弹框
 */
const openDialog = () => {
  // 查询案卷目录
  queryTree()
  // // 获取皮批量修改记录
  // getPlxgjl()
  // 批量修改字段分类代码
  getXgzd()
  dialogVisible.value = true
}

const xgfsList = ref<any[]>([
  {
    label: '固定填充',
    value: '1',
  },
  {
    label: '替换填充',
    value: '2',
  },
  {
    label: '追加填充',
    value: '3',
  },
])

// 修改字段change
const xglxNumber = ref<string | number>()
const xgzdChange = (index: number) => {
  form.value.xgzdmc = xgzdList.value[index].xgzdmc
  form.value.xgzddm = xgzdList.value[index].xgzddm
  xglxNumber.value = xgzdList.value[index].xglx
  if (xgzdList.value[index].xglx === '1') {
    xgfsList.value = [
      {
        label: '固定填充',
        value: '1',
      },
      {
        label: '替换填充',
        value: '2',
      },
      {
        label: '追加填充',
        value: '3',
      },
    ]
  } else {
    xgfsList.value = [
      {
        label: '固定填充',
        value: '1',
      },
      {
        label: '替换填充',
        value: '2',
      },
    ]
  }

  if (xgzdList.value[index].xglx === '4' && xgzdList.value[index].xgzddm === 'YSPLBMC') {
    getYsplb()
  } else if (xgzdList.value[index].xglx === '4' && xgzdList.value[index].xgzddm === 'MJMC') {
    getMj()
  } else if (xgzdList.value[index].xglx === '4' && xgzdList.value[index].xgzddm === 'BGQXMC') {
    getBgqx()
  }

  queryForm.value.tcnrValue = ''
  form.value.xgfsdm = '1'
  form.value.xgfsmc = '固定填充'
}

// 修改方式change
const xgfsChange = (val: string) => {
  queryForm.value.tcnrValue = ''
  queryForm.value.cznrValue = ''
  queryForm.value.thnrValue = ''
  queryForm.value.dqzjValue = ''
  queryForm.value.dhzjValue = ''
  let obj: any = {}
  obj = xgfsList.value.find((item: any) => {
    return item.value === val //筛选出匹配数据，这里的value是你遍历数组每一项的value，如果没有对后台返回的数据做处理，一般为id
  })
  form.value.xgfsdm = obj.value
  form.value.xgfsmc = obj.label
}

/*
 * 关闭弹框
 */
const closeDialog = () => {
  form.value = {
    gjz: '',
    xgfsdm: '1',
    xgfsmc: '固定填充',
    xgzddm: '',
    xgzdmc: '',
  }
  nodeValue.value = []

  dialogVisible.value = false
}

/*
 * 保存（成功抛出刷新）
 */
const save = () => {
  if (!nodeValue.value || nodeValue.value.length === 0)
    return ElMessage({ type: 'error', message: '请勾选目录' })

  if (!form.value.xgzddm) return ElMessage({ type: 'error', message: '请选择修改字段' })
  if (!form.value.xgfsdm) return ElMessage({ type: 'error', message: '请选择修改方式' })

  const params = {
    ajbh: store.$state.nodeTreeData?.ajbh as string,
    dhzj: queryForm.value.dhzjValue,
    dqzj: queryForm.value.dqzjValue,
    tcnr: queryForm.value.tcnrValue,
    thnr: queryForm.value.thnrValue,
    ccnr: queryForm.value.cznrValue,
    xgfsdm: form.value.xgfsdm,
    xgfsmc: form.value.xgfsmc,
    xgzddm: form.value.xgzddm,
    xgzdmc: form.value.xgzdmc,
    dabh: store.$state.nodeTreeData?.dabh,
    sxmlbhList: nodeValue.value.map((item: any) => item.bh),
  }
  dialogVisible.value = false
  yspglService
    .addSxplxgjl(params, route.query.ajbh as string)
    .then((res) => {
      if (res.code !== 0) {
        ElMessage({ type: 'error', message: res.message })
        return
      }
      ElMessage({ type: 'success', message: '保存成功' })
      emit('refresh')
      closeDialog()
    })
    .catch((err) => {
      !err.isError && ElMessage({ type: 'warning', message: err.message })
    })
}

// 文字过滤
const filtersTree = () => {
  treeRef.value?.filter(form.value.gjz)
}

// 填充内容
const queryForm = ref({
  tcnrValue: '',
  cznrValue: '',
  thnrValue: '',
  dqzjValue: '',
  dhzjValue: '',
})

const nodeValue = ref([])
const checkChange = (data: any, nonde: any) => {
  const node = nonde.checkedNodes
  nodeValue.value = node.filter((item: any) => item.cj === 2)
}

const kindList = ref<any>([])
// 获取密级分类代码
const getMj = async () => {
  kindList.value = await getFldm('gd006')
}
// 获取保管期限分类代码
const getBgqx = async () => {
  kindList.value = await getFldm('gd020')
}

// 获取音视频类别分类代码
const getYsplb = async () => {
  kindList.value = await getFldm('gd021')
}

const disabledDate = (time: any) => {
  return dayjs(time).valueOf() > dayjs().valueOf()
}

defineExpose({ openDialog })
</script>
<template>
  <el-dialog
    v-model="dialogVisible"
    title="批量修改"
    width="60%"
    :close-on-click-modal="false"
    :before-close="closeDialog"
  >
    <div class="dialog-content">
      <div class="left-tree">
        <el-tabs class="demo-tabs" type="card">
          <el-tab-pane label="音像">
            <div class="left-content">
              <header class="dialog-header">
                <el-input
                  v-model="form.gjz"
                  autosize=""
                  placeholder="请输入查询关键字"
                  @change="filtersTree"
                >
                  <template #suffix>
                    <el-icon @click="filtersTree" class="el-input__icon"><Search /></el-icon>
                  </template>
                </el-input>
              </header>
              <div class="tree-box">
                <el-tree
                  ref="treeRef"
                  style="max-width: 600px"
                  :data="treeData"
                  show-checkbox
                  draggable
                  node-key="bh"
                  highlight-current
                  :expand-on-click-node="false"
                  :props="defaultProps"
                  @node-click="treeNodeClick"
                  @check="checkChange"
                  :filter-node-method="filtersNode"
                >
                  <template #default="{ data }">
                    <div class="custom-tree-node">
                      <!-- <el-icon v-if="data.fbh"> <FolderOpened /></el-icon> -->
                      <img v-if="!data.fbh" src="/src/assets/images/file-icon.png" alt="" />
                      <img v-if="data.cj === 1" src="/src/assets/images/text-icon.png" alt="" />
                      <img
                        v-if="data.mllxmc === '视频' && data.sfxswj === 'Y'"
                        src="/src/assets/images/xssptb.png"
                        alt=""
                      />
                      <img
                        v-else-if="data.mllxmc === '视频' && (!data.sfxswj || data.sfxswj === 'N')"
                        src="/src/assets/images/xxsptb.png"
                        alt=""
                      />
                      <img
                        v-else-if="data.mllxmc === '音频' && data.sfxswj === 'Y'"
                        src="/src/assets/images/xsyptb.png"
                        alt=""
                      />
                      <img
                        v-else-if="data.mllxmc === '音频' && (!data.sfxswj || data.sfxswj === 'N')"
                        src="/src/assets/images/xxyptb.png"
                        alt=""
                      />
                      <img
                        v-else-if="data.mllxmc === '照片' && data.sfxswj === 'Y'"
                        src="/src/assets/images/xszptb.png"
                        alt=""
                      />
                      <img
                        v-else-if="data.mllxmc === '照片' && (!data.sfxswj || data.sfxswj === 'N')"
                        src="/src/assets/images/xxzptb.png"
                        alt=""
                      />
                      <!-- <el-icon v-if="data.zrz"> </el-icon> -->
                      <span :class="data.cj === 2 ? 'over-title' : ''" :title="data.mc"
                        >&nbsp;{{ data.mc }}&nbsp;</span
                      >
                      <span>({{ data.wjsl }})</span>
                    </div>
                  </template>
                </el-tree>
              </div>
            </div>
          </el-tab-pane>
        </el-tabs>
      </div>

      <div class="right-edit">
        <div class="edit-item">
          <span>修改字段:</span>
          <el-select
            v-model="form.xgzdmc"
            placeholder="请选择"
            style="width: 100%"
            @change="xgzdChange"
          >
            <el-option
              v-for="(zrritem, index) in xgzdList"
              :key="zrritem.xgzddm"
              :label="zrritem.xgzdmc"
              :value="index"
            >
            </el-option>
          </el-select>
        </div>
        <div class="edit-item edite-radio">
          <span class="edit-title">修改方式:</span>
          <!-- <el-radio-group v-model="form.xgfsdm" class="ml-4" @change="xgfsChange">
            <el-radio
              v-for="zrritem in xgfsList1"
              :key="zrritem.value"
              :value="zrritem.value"
              :label="zrritem.label"
            ></el-radio>
          </el-radio-group> -->
          <el-radio-group v-model="form.xgfsdm" class="ml-4" @change="xgfsChange">
            <el-radio
              v-for="zrritem in xgfsList"
              :key="zrritem.value"
              :value="zrritem.value"
              :label="zrritem.label"
            ></el-radio>
          </el-radio-group>
        </div>

        <div class="edit-item" v-if="form.xgfsdm === '1'">
          <span>填充内容:</span>
          <el-input
            v-if="xglxNumber === '1'"
            v-model="queryForm.tcnrValue"
            maxlength="30"
            placeholder="请输入"
          ></el-input>
          <el-date-picker
            v-if="xglxNumber === '2'"
            style="width: 100%"
            v-model="queryForm.tcnrValue"
            type="date"
            placeholder="请选择"
            value-format="YYYY-MM-DD"
            format="YYYY-MM-DD"
          />
          <el-input-number
            v-if="
              xglxNumber === '3' &&
              (form.xgzddm === 'XS' || form.xgzddm === 'FZ' || form.xgzddm === 'M')
            "
            v-model="queryForm.tcnrValue"
            :min="0"
            :max="99"
            :controls="false"
            style="width: 100%"
          ></el-input-number>
          <el-input-number
            v-if="xglxNumber === '3' && (form.xgzddm === 'ND' || form.xgzddm === 'WJDX')"
            v-model="queryForm.tcnrValue"
            :controls="false"
            style="width: 100%"
          ></el-input-number>
          <el-select
            v-if="xglxNumber === '4' && form.xgzddm !== 'WJGS'"
            v-model="queryForm.tcnrValue"
            clearable
            placeholder="请选择"
            style="width: 100%"
          >
            <el-option
              v-for="zrritem in kindList"
              :key="zrritem.dm"
              :label="zrritem.mc"
              :value="zrritem.mc"
            >
            </el-option>
          </el-select>

          <el-select
            v-if="xglxNumber === '4' && form.xgzddm === 'WJGS'"
            v-model="queryForm.tcnrValue"
            clearable
            placeholder="请选择"
            style="width: 100%"
          >
            <el-option label=".mp4" value="mp4"> </el-option>
            <el-option label=".mp3" value="mp3"> </el-option>
            <el-option label=".amr" value="amr"> </el-option>
            <el-option label=".m4a" value="m4a"> </el-option>
            <el-option label=".mov" value="mov"> </el-option>
            <el-option label=".mkv" value="mkv"> </el-option>
            <el-option label=".avi" value="avi"> </el-option>
            <el-option label=".wpl" value="wpl"> </el-option>
          </el-select>
        </div>

        <template v-if="form.xgfsdm === '2'">
          <div class="edit-item">
            <span>查找内容:</span>
            <el-input
              v-if="xglxNumber === '1' || xglxNumber === '3'"
              v-model="queryForm.cznrValue"
              maxlength="30"
            ></el-input>
            <el-date-picker
              v-if="xglxNumber === '2'"
              style="width: 100%"
              v-model="queryForm.cznrValue"
              type="date"
              placeholder="请选择"
              value-format="YYYY-MM-DD"
              format="YYYY-MM-DD"
            />
            <el-select
              v-if="xglxNumber === '4' && form.xgzddm !== 'WJGS'"
              v-model="queryForm.cznrValue"
              clearable
              placeholder="请选择"
              style="width: 100%"
            >
              <el-option
                v-for="zrritem in kindList"
                :key="zrritem.dm"
                :label="zrritem.mc"
                :value="zrritem.mc"
              >
              </el-option>
            </el-select>
            <el-select
              v-if="xglxNumber === '4' && form.xgzddm === 'WJGS'"
              v-model="queryForm.tcnrValue"
              clearable
              placeholder="请选择"
              style="width: 100%"
            >
              <el-option label=".mp4" value="mp4"> </el-option>
              <el-option label=".mp3" value="mp3"> </el-option>
              <el-option label=".amr" value="amr"> </el-option>
              <el-option label=".m4a" value="m4a"> </el-option>
              <el-option label=".mov" value="mov"> </el-option>
              <el-option label=".mkv" value="mkv"> </el-option>
              <el-option label=".avi" value="avi"> </el-option>
              <el-option label=".wpl" value="wpl"> </el-option>
            </el-select>
          </div>
          <div class="edit-item">
            <span>替换内容:</span>
            <el-input
              v-if="xglxNumber === '1' || xglxNumber === '3'"
              v-model="queryForm.thnrValue"
              maxlength="30"
            ></el-input>
            <el-date-picker
              v-if="xglxNumber === '2'"
              style="width: 100%"
              v-model="queryForm.thnrValue"
              type="date"
              placeholder="请选择"
              value-format="YYYY-MM-DD"
              format="YYYY-MM-DD"
            />
            <el-select
              v-if="xglxNumber === '4' && form.xgzddm !== 'WJGS'"
              v-model="queryForm.thnrValue"
              clearable
              placeholder="请选择"
              style="width: 100%"
            >
              <el-option
                v-for="zrritem in kindList"
                :key="zrritem.dm"
                :label="zrritem.mc"
                :value="zrritem.mc"
              >
              </el-option>
            </el-select>
            <el-select
              v-if="xglxNumber === '4' && form.xgzddm === 'WJGS'"
              v-model="queryForm.tcnrValue"
              clearable
              placeholder="请选择"
              style="width: 100%"
            >
              <el-option label=".mp4" value="mp4"> </el-option>
              <el-option label=".mp3" value="mp3"> </el-option>
              <el-option label=".amr" value="amr"> </el-option>
              <el-option label=".m4a" value="m4a"> </el-option>
              <el-option label=".mov" value="mov"> </el-option>
              <el-option label=".mkv" value="mkv"> </el-option>
              <el-option label=".avi" value="avi"> </el-option>
              <el-option label=".wpl" value="wpl"> </el-option>
            </el-select>
          </div>
        </template>
        <template v-if="form.xgfsdm === '3'">
          <div class="edit-item">
            <span>段前追加:</span>
            <el-input v-model="queryForm.dqzjValue" maxlength="30"></el-input>
          </div>
          <div class="edit-item">
            <span>段后追加:</span>
            <el-input v-model="queryForm.dhzjValue" maxlength="30"></el-input>
          </div>
        </template>
      </div>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="save">确定</el-button>
        <el-button @click="closeDialog">取消</el-button>
      </div>
    </template>
  </el-dialog>
</template>
<style lang="scss" scoped>
.dialog-content {
  width: 100%;
  height: 500px;
  display: flex;

  .left-tree {
    width: 50%;

    .left-content {
      display: flex;
      flex-direction: column;
      height: 100%;

      .dialog-header {
        height: 40px;
      }

      .tree-box {
        flex: 1;
        flex-shrink: 0;
        overflow: auto;
      }
    }
  }

  .right-edit {
    width: 50%;
    height: 100%;
    display: flex;
    flex-direction: column;
    justify-content: center;
    padding: 0 30px;

    .edit-item {
      display: flex;
      align-items: center;
      & > span {
        display: block;
        width: 100px;
      }
    }

    .el-radio-group {
      width: 100%;
    }

    .edit-item + .edit-item {
      margin-top: 15px;
    }

    .edite-radio {
      align-items: stretch;
    }
  }
}

.el-input__icon {
  cursor: pointer;
}

.custom-tree-node {
  width: calc(100% - 40px);
  display: flex;
  align-items: center;
  .over-title {
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
  }
}

:deep(.el-input-number .el-input__inner) {
  text-align: left;
}

:deep(.el-input__wrapper) {
  box-shadow: 0 0 0 1px var(--el-input-border-color) !important;
}

:deep(.el-select__wrapper) {
  box-shadow: 0 0 0 1px var(--el-border-color) !important;
}

:deep(.el-radio) {
  display: block;
  width: 50%;
}
</style>
